﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using static Lhxzn.LangExtractor.AITranslator;


#region 文件信息
/****************************************************************
*	公司名称：福建力和行智能科技有限公司
*   作    者：Jeff
*   CLR 版本：4.0.30319.42000
*   创建时间：1/10/2025 9:48:17 AM
*	用 户 名：zheqichen 
*   描述说明：
*
*   修改历史：
*		1）	修 改 人：
*			修改日期：
*			修改内容：			
*
*****************************************************************/
#endregion

namespace Lhxzn.LangExtractor
{
    /// <summary>
    /// 类    名:AITranslator
    /// 描    述:
    /// 修改时间:1/10/2025 9:48:17 AM
    /// </summary>
    public class AITranslator
    {
        #region 成员变量

        #region private
        // DeepSeek API 配置



        #endregion


        #region protected



        #endregion


        #region public

        public static AITranslator Instance { get; private set; }= new AITranslator();
        [Category("大模型接口信息")]
        [Description("DeepSeek的URL,通常为https://api.deepseek.com/chat/completions")]
        [DisplayName("URL")]
        public  string DeepSeekApiUrl { get; set; } = "https://api.deepseek.com/chat/completions";

        [Category("大模型接口信息")]
        [DisplayName("API密钥")]
        [Description("需要进入Deepseek官网注册获取")]
        public string ApiKey { get; set; } = "sk-907cf22020ad431d8306d638af1daa8b"; // 替换为你的 API 密钥

        [Category("请求信息")]
        [DisplayName("命令")]
        [Description("处理翻译文本的命令，描述清楚翻译的格式，领域等要求")]
        public string commandStr { get; set; } = "我需要翻译锂电池视觉检测软件，等号左边保持原文，右边翻译为英语，保持原文格式并且不要添加额外的空格和回车符号，不一定要完全符合原来的意思但是得简短，保证不要缺失翻译行";

        [Category("请求信息")]
        [DisplayName("单次请求最大行数")]
        [Description("文本内容过大，大模型处理不来时可以调小此参数，将一个大文本拆分多次发送请求")]
        public uint MaxProcessLength { get; set; } = 200;

        [Browsable(false)]
        public Action<ChatRecord> AIResponse;
        [Browsable(false)]
        public Action<ChatRecord> UserRequest;
        [Browsable(false)]
        public List<ChatRecord> ChatRecords=new List<ChatRecord>();

        public class ChatRecord
        {
            public string Name { get; set; }

            public ChatMessage User { get; set; }

            public ChatMessage Assistant { get; set; }

            public DateTime Time { get; set; }

            public ChatRecord(string nane,ChatMessage user, ChatMessage assistant)
            {
                Name = nane;
                User = user;
                Assistant = assistant;
                Time= DateTime.Now;
            }

            public override string ToString()
            {
                return Name;
            }
        }

        public class ChatMessage
        {
            [JsonProperty("role")]
            public string Role { get; set; } // "user" 或 "assistant"

            [JsonProperty("content")]
            public string Content { get; set; }
        }


        public class ChatResponse
        {
            [JsonProperty("choices")]
            public List<ChatChoice> Choices { get; set; }
        }

        public class ChatChoice
        {
            [JsonProperty("message")]
            public ChatMessage Message { get; set; }
        }

        public class CommandInfo
        {
            public string Name { get; set; }

            public string Command { get; set; }

            public string ProcessContent { get; set; }
        }
        #endregion

        #endregion


        #region 构造函数
        /// <summary>
        /// 函 数 名:构造函数
        /// 函数描述:默认构造函数
        /// 修改时间:1/10/2025 9:48:17 AM
        /// </summary>
        public AITranslator()
        {
        }
        #endregion

        #region 父类函数重载、接口实现
        #endregion

        #region 函数

        #region private



        #endregion


        #region protected



        #endregion


        #region public
        /// <summary>
        /// 保存到文件夹
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static async Task SaveChatRecordsToDirectoryAsync(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            foreach (var record in Instance.ChatRecords)
            {
                if (string.IsNullOrEmpty(record.Assistant.Content))
                {
                    continue;
                }
                string fileName = Path.Combine(folderPath, record.Name);
                await File.WriteAllTextAsync(fileName, record.Assistant.Content);
            }
        }

        /// <summary>
        /// 保存到工作台语言包
        /// </summary>
        /// <param name="package"></param>
        public static void SaveChatRecordsToLngPak(LanguagePackage package)
        {
            if(package==null|| package.LanguageFiles == null)
            {
                return;
            }

            foreach (var record in Instance.ChatRecords)
            {
                string name = Path.GetFileNameWithoutExtension(record.Name);
                var lngFile=package.LanguageFiles.FirstOrDefault(f => f.Name == name);
                if (lngFile == null|| string.IsNullOrEmpty(record.Assistant.Content))
                {
                    continue;
                }
                lngFile.Reload(record.Assistant.Content);
            }
        }

        /// <summary>
        /// 异步读取文件夹内的语言文件并翻译
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="userCommand"></param>
        /// <returns></returns>
        public static async Task<string[]> AnalyzeFolderAsync(string folderPath,string userCommand= "")
        {
            if (string.IsNullOrEmpty(userCommand))
            {
                userCommand = Instance.commandStr;
            }
            List<Task<string>> tasks = new List<Task<string>>();
            foreach (string filePath in Directory.GetFiles(folderPath, "*.lng")) // 仅处理 .lng 文件
            {
                Task<string> task =  AnalyzeFileAsync(filePath, userCommand);
                tasks.Add(task);
            }
            string[] results = await Task.WhenAll(tasks);
            return results;
        }

        /// <summary>
        /// 异步读取语言包内的文件并翻译
        /// </summary>
        /// <param name="package"></param>
        /// <param name="userCommand"></param>
        /// <returns></returns>
        public static async Task<string[]> AnalyzeLanguagePakAsync(LanguagePackage package, string userCommand = "")
        {
            if (string.IsNullOrEmpty(userCommand))
            {
                userCommand = Instance.commandStr;
            }
            List<Task<string>> tasks = new List<Task<string>>();
            foreach (var file in package.LanguageFiles) // 仅处理 .lng 文件
            {
                CommandInfo commandInfo = new CommandInfo()
                {
                    Command = userCommand,
                    ProcessContent = file.GetText(),
                    Name = Path.GetFileName(file.FilePath)
                };
                Task<string> task= AnalyzeWithDeepSeekAsync(commandInfo);
                tasks.Add(task);
            }
            string[] results = await Task.WhenAll(tasks);
            return results;
        }

        /// <summary>
        /// 异步读取语言文件并翻译
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="userCommand"></param>
        /// <returns></returns>
        public static async Task<string> AnalyzeFileAsync(string filePath, string userCommand= "")
        {
            if (string.IsNullOrEmpty(userCommand))
            {
                userCommand = Instance.commandStr;
            }
            // 读取文件内容
            string fileContent = await File.ReadAllTextAsync(filePath, Encoding.UTF8);
            CommandInfo commandInfo = new CommandInfo()
            {
                Command = userCommand,
                ProcessContent = fileContent,
                Name = Path.GetFileName(filePath)
            };
            // 调用 DeepSeek API 分析文件内容和用户命令
            string analysisResult = await AnalyzeWithDeepSeekAsync(commandInfo);
            return analysisResult;
        }

        /// <summary>
        /// 分析多个文本，带分析事件
        /// </summary>
        /// <param name="commandInfo"></param>
        /// <returns></returns>
        public static async Task<string> AnalyzeWithDeepSeekAsync(CommandInfo commandInfo)
        {
            ChatMessage userChat = new ChatMessage { Role = "user", Content = commandInfo.Command + "\n" + commandInfo.ProcessContent };
            List<ChatMessage> chatMessages = new List<ChatMessage>() { userChat };
            ChatMessage assistantChat = new ChatMessage { Role = "assistant", Content = "等待AI翻译中...." };
            ChatRecord record = new ChatRecord(commandInfo.Name, userChat, assistantChat);
            Instance.ChatRecords.Add(record);
            Instance.UserRequest?.Invoke(record);
            // 分割过长内容
            string compeleteResponse = await AnalyzeLargeTextAsync(commandInfo.Command, commandInfo.ProcessContent);

            //double random = new Random().NextDouble();
            //int sleepTime = (int)(random * 10000);
            //Thread.Sleep(sleepTime);
            //string compeleteResponse= Instance.textTemp;//测试使用

            assistantChat.Content = compeleteResponse;
            Instance.AIResponse?.Invoke(record);

            return compeleteResponse;
        }

        /// <summary>
        /// 分析文本过长的内容使用的函数
        /// </summary>
        /// <param name="command"></param>
        /// <param name="processContent"></param>
        /// <returns></returns>
        public static async Task<string> AnalyzeLargeTextAsync(string command, string processContent)
        {
            int MaxProcessCount = (int)Instance.MaxProcessLength;
            string[] splitStrs = new string[] { "\n", "\r\n", "\v" };
            string[] lines = processContent.Split(splitStrs, StringSplitOptions.None);
            List<string> splitPostStrs = new List<string>();
            int processCount = lines.Length / MaxProcessCount + (lines.Length % MaxProcessCount != 0 ? 1 : 0);
            for (int i = 0; i < processCount; i++)
            {
                int start = i * MaxProcessCount;
                int end = Math.Min(start + MaxProcessCount, lines.Length);
                string segment = string.Join(Environment.NewLine, lines, start, end - start);
                string splitPostStr = command + "\n" + segment;
                splitPostStrs.Add(splitPostStr);
            }

            string compeleteResponse = "";
            foreach (string str in splitPostStrs)
            {
                string oneResponse = await AnalyzeWithDeepSeekAsync(str);
                compeleteResponse += compeleteResponse == "" ? oneResponse : "\n" + oneResponse;
            }
            return compeleteResponse;
        }

        /// <summary>
        /// 单次访问大模型函数，最多单次处理300行的内容
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public static async Task<string> AnalyzeWithDeepSeekAsync(string post)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Instance.ApiKey);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                ChatMessage userChat = new ChatMessage { Role = "user", Content = post };
                List<ChatMessage> chatMessages = new List<ChatMessage>() { userChat };
                var requestBody = new
                {
                    model = "deepseek-chat",
                    messages = chatMessages,
                    stream = false
                };
                string jsonBody = JsonConvert.SerializeObject(requestBody);

               HttpResponseMessage response = await client.PostAsync(
                   Instance.DeepSeekApiUrl,
                   new StringContent(jsonBody, Encoding.UTF8, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ChatResponse>(jsonResponse);
                    string botResponse = result?.Choices[0].Message.Content ?? "未收到有效回复";
                    return botResponse;
                }
                else
                {
                    string responseStr= await response.Content.ReadAsStringAsync();
                    return $"对话失败，请检查 API 调用,{response.StatusCode},{responseStr}";
                }
            }
        }


        /// <summary>
        /// 重置
        /// </summary>
        public static void Reset()
        {
            Instance.ChatRecords.Clear();
            Instance.AIResponse = null;
            Instance.UserRequest = null;
        }


        //public static async Task<string> AnalyzeWithDeepSeekAsync(CommandInfo commandInfo)
        //{
        //    using (HttpClient client = new HttpClient())
        //    {
        //        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Instance.ApiKey);
        //        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //        ChatMessage userChat = new ChatMessage { Role = "user", Content = commandInfo.Command + "\n" + commandInfo.ProcessContent };
        //        List<ChatMessage> chatMessages = new List<ChatMessage>() { userChat };
        //        var requestBody = new
        //        {
        //            model = "deepseek-chat",
        //            messages = chatMessages,
        //            stream = false
        //        };
        //        string jsonBody = JsonConvert.SerializeObject(requestBody);
        //        ChatMessage assistantChat = new ChatMessage { Role = "assistant", Content = "等待AI翻译中...." };
        //        ChatRecord record = new ChatRecord(commandInfo.Name, userChat, assistantChat);
        //        Instance.ChatRecords.Add(record);
        //        Instance.UserRequest?.Invoke(record);
        //        //double random = new Random().NextDouble();
        //        //int sleepTime = (int)(random * 10000);
        //        //Thread.Sleep(sleepTime);
        //        //assistantChat.Content = "AI翻译完成";//test
        //        //Instance.AIResponse?.Invoke(record);
        //        //return "";
        //        HttpResponseMessage response = await client.PostAsync(
        //           Instance.DeepSeekApiUrl,
        //           new StringContent(jsonBody, Encoding.UTF8, "application/json")
        //       );

        //        if (response.IsSuccessStatusCode)
        //        {
        //            string jsonResponse = await response.Content.ReadAsStringAsync();
        //            var result = JsonConvert.DeserializeObject<ChatResponse>(jsonResponse);

        //            // 将模型的回复添加到对话上下文
        //            string botResponse = result?.Choices[0].Message.Content ?? "未收到有效回复";
        //            assistantChat.Content = botResponse;
        //            Instance.AIResponse?.Invoke(record);
        //            return botResponse;
        //        }
        //        else
        //        {
        //            string responseStr = await response.Content.ReadAsStringAsync();
        //            return $"对话失败，请检查 API 调用,{response.StatusCode},{responseStr}";
        //        }

        //    }
        //}

        #endregion

        #endregion
    }
}
